//
//  ViewController.m
//  ExampleDemo
//
//  Created by wulanzhou on 16/6/15.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "ViewController.h"
#import "SVProgressHUD.h"
#import "BLEKiApiObject.h"
#import "SkySimViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //设置cell高度
    self.deviceTable.rowHeight=50.0f;
    
    //扫描蓝牙(扫描到蓝牙sim卡后，如果3秒内没有扫描到其它设备，则会自动连接,如果扫描到多个则走setDeviceScanCompletionBlock)
    [[BLECentralManager shareInstance] startScan];
    
    
    
    //蓝牙状态(对应通知kBLEStateChangedNotification)
    [[BLECentralManager shareInstance] setStateChangedBlock:^(BLEState bleState){
    
        if (bleState!=BLEStateOpen) {
            [SVProgressHUD showInView:self.view];
            [SVProgressHUD dismissWithError:@"蓝牙未开启" afterDelay:2.0f];
        }
    }];
    
    //蓝牙扫描到多个连接选择(对应通知kBLEScanCompletedNotification)
    [[BLECentralManager shareInstance] setDeviceScanCompletionBlock:^(NSArray *devices) {
        self.listData=devices;
        [self.deviceTable reloadData];
        
        if ([self.navigationController.topViewController isKindOfClass:[SkySimViewController class]]){
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    //蓝牙连接成功(对应通知kBLEConnectSetupNotification)
    [[BLECentralManager shareInstance] setConnectedCompletionBlock:^(CBPeripheral *peripheral) {
        
        [SVProgressHUD showInView:self.view];
        [SVProgressHUD dismissWithSuccess:@"蓝牙连接成功" afterDelay:2.0f];
        //连接成功后跳转到下一页
        [self performSelector:@selector(goSkySimPage) withObject:nil afterDelay:2.0f];
    }];
    
    //蓝牙连接失败(对应通知kBLEConnectFailedNotification)
    [[BLECentralManager shareInstance] setConnectFailedBlock:^(CBPeripheral *peripheral, NSError *error) {
        [SVProgressHUD showInView:self.view];
        [SVProgressHUD dismissWithError:@"蓝牙连接失败" afterDelay:2.0f];
        NSLog(@"蓝牙连接失败=%@",error);
    }];
     
    
    
    /**
     
     也可以使用通知处理：
     
    [self addObservers];
      
     **/
    
    
    
   
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -注册通知

- (void)addObservers{
    //蓝牙状态变更
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveStateChangeNotify:) name:kBLEStateChangedNotification object:nil];
    
    //蓝牙扫描到多个连接选择通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveDevicesNotify:) name:kBLEScanCompletedNotification object:nil];
    
    //蓝牙建立连接
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveConnectNotify:) name:kBLEConnectSetupNotification object:nil];
    
    //蓝牙连接失败
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveConnectFailedNotify:) name:kBLEConnectFailedNotification object:nil];
}

#pragma mark 事件

//扫描
- (IBAction)startScanClick:(id)sender {
    //扫描蓝牙
    [[BLECentralManager shareInstance] startScan];
}

//页面跳转
- (void)goSkySimPage{
    
    if (![self.navigationController.topViewController isKindOfClass:[SkySimViewController class]]) {
        SkySimViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:@"SkySimVC"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark -通知处理

//蓝牙状态变更通知
- (void)receiveStateChangeNotify:(NSNotification *)notify{

    if ([[notify object] integerValue]!=BLEStateOpen) {
        [SVProgressHUD showInView:self.view];
        [SVProgressHUD dismissWithError:@"蓝牙未开启" afterDelay:2.0f];
    }
}

//蓝牙扫描到多个连接选择通知
- (void)receiveDevicesNotify:(NSNotification *)notify{
    self.listData=(NSArray *)[notify object];
    [self.deviceTable reloadData];
    
    if ([self.navigationController.topViewController isKindOfClass:[SkySimViewController class]]){
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//蓝牙连接成功
- (void)receiveConnectNotify:(NSNotification *)notify{
    
    [SVProgressHUD showInView:self.view];
    [SVProgressHUD dismissWithSuccess:@"蓝牙连接成功" afterDelay:2.0f];
    //连接成功后跳转到下一页
    [self performSelector:@selector(goSkySimPage) withObject:nil afterDelay:2.0f];
    
}
//蓝牙连接失败
- (void)receiveConnectFailedNotify:(NSNotification *)notify{

    [SVProgressHUD showInView:self.view];
    [SVProgressHUD dismissWithError:@"蓝牙连接失败" afterDelay:2.0f];
}


#pragma mark - Table Source & Delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    BLEDeviceInfo *info =self.listData[indexPath.row];
    cell.textLabel.text = [info getDeviceName];
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.listData count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //连接设备
    BLEDeviceInfo *info =self.listData[indexPath.row];
    [[BLECentralManager shareInstance] beginConnectWithPeripheral:info.peripheral];
    
}

@end
